package com.yc.jpyy.mobile.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.mobile.dao.BizDao;
import com.yc.jpyy.mobile.service.BizService;


@Controller
@RequestMapping(value = "/Alipay")
public class AlipayController extends BaseController{
	
	@Autowired
	private BizService bizService;
	@Autowired
	private BizDao bizDao;
	
	
	 /*
	  * * 调用支付宝统一下单接口返回订单信息接口
	  */
	 
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getOrderInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String getOrderInfo(HttpServletRequest request)
			throws UnsupportedEncodingException {
		
		RestResponse response = new RestResponse();
		
		try {
			//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body。
			String body = request.getParameter("body");
			//商品的标题/交易标题/订单标题/订单关键字等。
			String subject = request.getParameter("subject");
			//商户网站唯一订单号
			String out_trade_no = request.getParameter("out_trade_no");
			//订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
			String total_amount = request.getParameter("total_amount");
			
			//实例化客户端
			AlipayClient alipayClient = new DefaultAlipayClient(Config.getAlipayUrl(), 
					Config.getAlipayAppId(), Config.getRSASecret(), "json", Config.getAlipayKey(), "RSA2");
			//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
			AlipayTradeAppPayRequest requests = new AlipayTradeAppPayRequest();
			//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
			AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
			model.setBody(body);
			model.setSubject(subject);
			model.setOutTradeNo(out_trade_no);
			//model.setTimeoutExpress("30m");
			model.setTotalAmount(total_amount);
			//销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
			model.setProductCode("QUICK_MSECURITY_PAY");
			requests.setBizModel(model);
			//异步通知回调地址
			requests.setNotifyUrl(Config.getNotifyUrl());
			//这里和普通的接口调用不同，使用的是sdkExecute
	        AlipayTradeAppPayResponse responses = alipayClient.sdkExecute(requests);
	        //就是orderString 可以直接给客户端请求，无需再做处理。
	        System.out.println(responses.getBody());
	        //返回订单信息
	        response.setErrorcode(0);
	        response.setData(responses.getBody());
		} catch (Exception e) {
			response.setErrorcode(1);
			response.setMessage("获取支付订单失败！");
		}finally {
			return response.toJSON();
		}		
	}
	
	/*
	 * 异步回调通知接口
	 * 
	 */
	 
	@SuppressWarnings("finally")
	@RequestMapping(value = "/notify", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String notify(HttpServletRequest request){
		try {
			Map<String,String> params = new HashMap<String,String>();
			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			    String name = (String) iter.next();
			    String[] values = (String[]) requestParams.get(name);
			    String valueStr = "";
			    for (int i = 0; i < values.length; i++) {
			        valueStr = (i == values.length - 1) ? valueStr + values[i]
			                    : valueStr + values[i] + ",";
			  	}
			    //乱码解决，这段代码在出现乱码时使用。
				//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}
			//验签，切记alipaypublickey是支付宝的公钥
			boolean flag = AlipaySignature.rsaCheckV1(params, Config.getAlipayAppId(), "utf-8","RSA2");
	        if(flag){
	        	//验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
	            String tradeStatus = params.get("trade_status");
	            String tradeNo = request.getParameter("out_trade_no"); 
	            if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {  
                    //要写的逻辑。自己按自己的要求写
                }  
	            return  "success";
	        }else{
	        	//验签失败则记录异常日志，并在response中返回failure.
	            return "failure";
	        }
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			return "failure";
		}
	}
	
}